//
//  PoiFavViewController.m
//  FootPrint
//
//  Created by 秦 东方 on 4/10/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "PoiFavViewController.h"
#import "MerchantCell.h"
#import "DDAlertPrompt.h"
#import "PIODetailViewController.h"

@interface PoiFavViewController ()

@end

@implementation PoiFavViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _parser = [[FavMerchantParser alloc] init];
        [_parser setDelegate:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    _favMer = [[NSMutableArray alloc] initWithCapacity:15];
    _waitingServer = true;
    [_tableFav setDelegate:self];
    [_tableFav setDataSource:self];
    
    [_parser reqFavMerchant:[GConfig getUserId]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:NOTIFY_REFRESH_FAV object:nil];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)refreshData{
    [_parser reqFavMerchant:[GConfig getUserId]];
}


- (void)setMode:(PoiOpenMode)openMode{
    _mode = openMode;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) updateCell : (UITableViewCell*) cell withData : (MerchantMessage*)mer{
    FPImageView* icon = (FPImageView*)[cell viewWithTag:0];
    UITextView* title = (UITextView*)[cell viewWithTag:1];
    UITextView* content = (UITextView*)[cell viewWithTag:2];
    [icon loadAsyncImage: [ [mer logo] imageUrl ] ];
    [title setText:[mer name]];
    [content setText:[mer address]];
}

#pragma mark datasouce
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(_waitingServer){
        return 1;
    }
    return [[_msgFav merchant] count] + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_waitingServer){
        
        NSArray *arr = [[NSBundle mainBundle] loadNibNamed:@"LoadingCell" owner:self options:nil];
		UITableViewCell* cell = (UITableViewCell*)[arr objectAtIndex:0];
        UIActivityIndicatorView *ai = (UIActivityIndicatorView *)[cell viewWithTag:1];
        [ai startAnimating];
        return cell;
       
    }
    if(indexPath.row == 0){
        NSArray *arr = [[NSBundle mainBundle] loadNibNamed:@"AddMerCell" owner:self options:nil];
		UITableViewCell* cell = (UITableViewCell*)[arr objectAtIndex:0];
        return cell;
    }
    
    static NSString *identify = @"merchantCell";
    MerchantCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if(nil == cell){
        cell = [[[MerchantCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify] autorelease];
    }
    //NSInteger index = indexPath.row - 1;
    MerchantMessage* mer = (MerchantMessage*)[[_msgFav merchant] objectAtIndex:indexPath.row - 1]; 
    [cell updateCell:mer];
    return cell;

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 0){
        return 50;
    }
    return 65;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(_waitingServer){
        return;
    }
    //int index = indexPath.row;
    if(indexPath.row == 0){//添加商户
        
        DDAlertPrompt *loginPrompt = [[DDAlertPrompt alloc] initWithTitle:@"新建商户" delegate:self cancelButtonTitle:@"取消" otherButtonTitle:@"提交"];
        [loginPrompt show];
        [loginPrompt release];
        
    } else { //操作一个item
    
        _selectIndex = indexPath.row;
        UIActionSheet* sheet = [[[UIActionSheet alloc] initWithTitle:nil
                                                           delegate:self
                                                  cancelButtonTitle:nil
                                             destructiveButtonTitle:nil
                                                  otherButtonTitles:nil] autorelease];
        if(_mode == ModeChoose){
            PIODetailViewController * poiVC = [[[PIODetailViewController alloc] initWithNibName:@"PIODetailViewController" bundle:nil] autorelease];
            [poiVC setSelDelegate:_selDelegate];
            
            UINavigationController * navVc = ((UIViewController*)self.selDelegate).navigationController;
            [navVc pushViewController:poiVC animated:YES];
            
            MerchantMessage* mer = (MerchantMessage*)[[_msgFav merchant] objectAtIndex:_selectIndex - 1];
            [poiVC updatePOIInfo:mer];
            poiVC.btnChoose.hidden = YES;
            poiVC.btnFav.hidden = YES;
            return;
        } else {
            [sheet addButtonWithTitle:@"查看"];
        }
        
        [sheet addButtonWithTitle:@"删除"];
        [sheet addButtonWithTitle:@"取消"];
        sheet.cancelButtonIndex = [sheet numberOfButtons] - 1;
        [sheet showInView:self.view];
    }
    
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString* title = [actionSheet buttonTitleAtIndex:buttonIndex];
    if(NSOrderedSame == [title compare:@"查看"]){
        PIODetailViewController * poiVC = [[[PIODetailViewController alloc] initWithNibName:@"PIODetailViewController" bundle:nil] autorelease];
        
        UINavigationController * navVc = ((UIViewController*)self.selDelegate).navigationController;
        [navVc pushViewController:poiVC animated:YES];

        MerchantMessage* mer = (MerchantMessage*)[[_msgFav merchant] objectAtIndex:_selectIndex - 1];
        [poiVC updatePOIInfo:mer];
        poiVC.btnChoose1.hidden = YES;
        poiVC.btnChoose.hidden = YES;
        poiVC.btnFav.hidden = YES;
        //TODO 跳转
    } else if(NSOrderedSame == [title compare:@"删除"]){
        MerchantMessage* mer = (MerchantMessage*)[[_msgFav merchant] objectAtIndex:_selectIndex - 1]; 
        [_parser reqDelFav:[GConfig getUserId] merId: [mer id] ];
    } else if(NSOrderedSame == [title compare:@"选择"]){
        int tempIndex = _selectIndex - 1.0;
        MerchantMessage* mer = (MerchantMessage*)[[_msgFav merchant] objectAtIndex:tempIndex];
        [_selDelegate didSelPOI:mer];
    }
    
}

#pragma mark call back of alert view

- (void)didPresentAlertView:(UIAlertView *)alertView {
	if ([alertView isKindOfClass:[DDAlertPrompt class]]) {
		DDAlertPrompt *addMerPrompt = (DDAlertPrompt *)alertView;
		[addMerPrompt.plainTextField becomeFirstResponder];
		[addMerPrompt setNeedsLayout];
	}
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
	if (buttonIndex == [alertView cancelButtonIndex]) {
        
	} else {
		if ([alertView isKindOfClass:[DDAlertPrompt class]]) {
			DDAlertPrompt *addMerPrompt = (DDAlertPrompt *)alertView;
            NSString* name = addMerPrompt.plainTextField.text;
            NSString* addr = addMerPrompt.secretTextField.text;
			
            if(nil == name || name.length < 1){
                [[[iToast makeText:@"商户名不能为空!"] setDuration:2000] show];
            }
            
            [_parser reqAddMerchant:[GConfig getUserId] name:name address:addr];
            
		}
	}
}



#pragma mark server call back

- (void) didFinishReqFav : (UserFavoriteMerchantQueryResponseMessage*) favMerchants{
    _waitingServer = NO;
    if(nil != favMerchants && [favMerchants resultCode] == 0){
        self.msgFav = favMerchants;
        [_tableFav reloadData];
    } else {
        [_tableFav reloadData];
        [[[iToast makeText:@"服务器出错，获取收藏信息失败"] setDuration:2000] show];
    }
    
    
}
- (void) failReqFav{
    _waitingServer = NO;
    [_tableFav reloadData];
    [[[iToast makeText:@"服务器出错，获取收藏信息失败"] setDuration:2000] show];
}



- (void)didFinishAddMer:(CustomizedMerchantResponseMessage*)addResp{
        
    if(nil != addResp && [addResp resultCode] == 0){
        [_parser reqAddFav: [GConfig getUserId] merId:[addResp merchantId]];
    } else {
        [[[iToast makeText:@"服务器出错，添加商户出错"] setDuration:2000] show];
    }

}
- (void)failAddMer{
    [[[iToast makeText:@"服务器出错，添加商户失败"] setDuration:2000] show];
}



- (void)didFinishAddFav:(UserFavoriteMerchantResponseMessage*)addFavResp{
    if(nil != addFavResp && [addFavResp resultCode] == 0){
        [[[iToast makeText:@"添加商户到收藏成功"] setDuration:2000] show];
        [_parser reqFavMerchant:[GConfig getUserId]];
    } else {
        [[[iToast makeText:@"服务器出错，添加到收藏失败"] setDuration:2000] show];
    }
}
- (void)failAddFav{
    [[[iToast makeText:@"服务器出错，添加到收藏失败"] setDuration:2000] show];
}


- (void)didFinishDel:(UserFavoriteMerchantDelResponseMessage*)delFavResp{
    if(nil != delFavResp && [delFavResp resultCode] == 0){
        [[[iToast makeText:@"删除成功"] setDuration:2000] show];
        [_parser reqFavMerchant:[GConfig getUserId]];
    } else {
        [[[iToast makeText:@"服务器出错，删除失败"] setDuration:2000] show];
    }
}
-(void)failDelFav{

    [[[iToast makeText:@"服务器出错，删除失败"] setDuration:2000] show];
}



- (void)dealloc {
    _selDelegate = nil;
    [_parser release];
    [_tableFav release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setTableFav:nil];
    [super viewDidUnload];
}
@end
